let Promises = Promise

Promises.prototype.finally = function(callback) {
	let P = this.constructor
	return this.then(
		value => P.resolve(callback()).then(() => value),
		reason => P.resolve(callback()).then(() => {
			throw reason
		}))
}

class Https {
	host() {
		return host
	}
	request(url, method, data, status, loading) {
		const openid = uni.getStorageSync('openid') || '' // 用户openid
		// const openid = 'oMbF5678aKoV1iW4tSeDFodT0KH0'

		if (!loading) {
			uni.showLoading()
		}
    console.log("请求接口：", url);
    console.log("请求入参：", JSON.stringify(data));
		return new Promises((resolve, reject) => {
			uni.request({
				url: url, // 接口地址
				method: method, // 接口类型
				data: {
					...data,
					'openid': openid,
				},
				header: {
					// 'content-type': 'application/x-www-form-urlencoded' // 默认值
				},
				beforeSend: function(request) {
					request.setRequestHeader("X-Requested-With", "XMLHttpRequest")
				},
				success: function(res) {
					if (!loading) {
						uni.hideLoading() // 关闭加载中
					}
          
          console.log("响应接口：", url);
          console.log("响应反参：", res);
          if (typeof res.data === 'string') {
            reject({ errMsg: '服务器异常' });
            return;
          }

					if (res.data.code === 20000) {
						resolve(res.data)
					} else {
						if (res.data.error_code === 401) {
							// 登录失效
						}

						if (status) {
							resolve(res.data)
						}

						getApp().getMsg(res.data.msg)
					}
				},
				fail: function(error) {
					uni.hideLoading() // 关闭加载中
          console.log("异常接口：", url);
          console.log("异常信息：", error);
					getApp().getMsg(error.errMsg ? error.errMsg : '请求失败')
					reject(error)
				}
			})
		})
	}

	get(url, data) {
		return this.request(url, 'GET', data)
	}

	post(url, data, status, loading) {
		return this.request(url, 'POST', data, status, loading)
	}
}

const https = new Https()

export default https